<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" @ok="handleSubmit" width="700px" destroyOnClose>
    <BasicForm @register="registerForm" />
    <Divider>消息字段配置</Divider>
    <JVxeTable
      ref="tableRef"
      stripe
      toolbar
      keepSource
      rowSelection
      asyncRemove
      dragSort
      sortKey="sortNo"
      rowKey="key"
      :auto-resize="true"
      :sync-resize="state.activeKey"
      :maxHeight="600"
      :disabledRows="{ isPk: [true] }"
      :loading="state.loading"
      :disabled="state.disabled"
      :columns="state.columns"
      :dataSource="state.dataSource"
      @removed="handleRemove"
      v-bind="gridOptions"
    >
      <template #toolbarSuffix>
        <a-button v-if="useIam().isAppHubOrMgt()" preIcon="ant-design:edit-outlined" @click="() => openFieldLibraryList(true, {})"> 字段库 </a-button>
      </template>
    </JVxeTable>
  </BasicDrawer>
  <FieldLibraryList @register="registerFieldLibraryList" @success="handleSelectField" showFooter />
</template>
<script lang="ts" setup>
  import { ref, computed, unref, watch, reactive } from "vue"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import FieldLibraryList from "./FieldLibraryList.vue"
  import { isString, isArray } from "/@/utils/is"
  import { Divider } from "ant-design-vue"
  import { formSchema } from "../data"
  import { saveOrUpdateNotice, getNotice, listChannel } from "../api"
  import { JVxeTypes, JVxeColumn } from "/@/components/jeecg/JVxeTable/types"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { useModal } from "/@/components/Modal"
  import { useUserStore } from "/@/store/modules/user"
  import { VxeGridProps } from "vxe-table"
  import { useIam } from '/@/hooks/web/useIam'

  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])

  const [registerFieldLibraryList, { openModal: openFieldLibraryList }] = useModal()
  const isUpdate = ref(true)

  const tableRef = ref()
  const vxeColumns: JVxeColumn[] = [
    {
      title: "名称",
      key: "desc",
      type: JVxeTypes.input,
      width: 230,
      validateRules: [{ required: true, message: "${title}不能为空" }],
    },
    {
      title: "消息字段",
      key: "key",
      type: JVxeTypes.input,
      width: 230,
      validateRules: [{ required: true, message: "${title}不能为空" }],
    },
    {
      title: "可编辑模板内容",
      key: "editTpl",
      type: JVxeTypes.checkbox,
      defaultValue: "1",
      validateRules: [{ required: true, message: "${title}不能为空" }],
      align: "center",
    },
  ]

  interface State {
    loading: boolean
    columns: JVxeColumn[]
    activeKey: string
    dataSource: Recordable[]
    toolbarConfig?: any
    deleted?: boolean
    disabled?: boolean
  }

  const state = ref<State>({
    loading: false,
    columns: vxeColumns,
    activeKey: "",
    dataSource: [],
    deleted: false,
    disabled: false,
  })

  const gridOptions = ref<VxeGridProps<any>>({
    editConfig: {
      trigger: "click",
      mode: "row",
    },
    checkboxConfig: {
      range: true,
      checkAll: false,
      // 默认勾选指定行（只会在初始化时被触发一次，需要有 row-config.keyField）
      // 这里为了使在设置初始化选中的行, 需要先不让视图渲染, 所以要设置 成v-if = false, 因为vux-table只会执行一次
      // 当初始化选中中行后再设置成true
      checkRowKeys: [],
      // 用于禁止某一行
      checkMethod: ({ row }) => {
        return useIam().isAppHubOrMgt() ? true : false
      },
    },
  })

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: formSchema,
    labelWidth: 90,
    showActionButtonGroup: false,
    labelCol: {
      xs: { span: 4 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  })

  const validateAttrValue = async (callback: Function) => {
    const values = tableRef.value!.getTableData()
    for (const item in values) {
      const errMap = await tableRef.value!.validateTable(values[item])
      if (errMap) {
        console.log("表单验证未通过：", { errMap })
        if (callback) {
          callback()
        }
        await tableRef.value!.validateTable()
        throw new Error(errMap)
      }
    }
    return values
  }
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    try {
      console.log("data", data)

      setDrawerProps({ confirmLoading: true })
      isUpdate.value = !!data?.isUpdate

      if (unref(isUpdate)) {
        const record = await getNotice({ id: data.record.id })
        if (!record) {
          return
        }
        state.value.deleted = record?.deleted
        state.value.dataSource = record.msgFields
        state.value.disabled = !useIam().isAppHubOrMgt()
        await setFieldsValue({ ...record })
      }
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  })

  const title = computed(() => (!unref(isUpdate) ? "新增消息通知" : state.value.deleted ? "编辑消息通知【已被删除】" : "编辑消息通知"))

  async function handleSubmit(v) {
    try {
      await validateAttrValue(() => {})
      const msgFields = tableRef.value!.getTableData()

      let values = await validate()
      const channelTypes = isArray(values.channelTypes) ? values.channelTypes : values.channelTypes.split(",")
      values = { ...values, templateConfig: JSON.stringify({}), channelTypes, msgFields }
      console.log("form: ", values)
      setDrawerProps({ confirmLoading: true })

      await saveOrUpdateNotice(
        {
          ...values,
        },
        isUpdate.value
      )
      closeDrawer()
      emit("success")
      createMessage.success(`${title.value}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const handleRemove = async () => {
    await tableRef.value!.removeSelection()
  }

  const handleSelectField = (data) => {
    tableRef.value.removeRows(data)
    tableRef.value.addRows(data)
  }
</script>

<style lang="less">
  .select-channel {
    color: #40a9ff;
    margin-left: 1px;
    cursor: pointer;
    font-size: 14px;
  }
</style>
